﻿CREATE PROCEDURE [dbo].[RestoreBackup]
	@backupFile NVARCHAR(2000),
	@dbName NVARCHAR(2000),
	@dbFolder NVARCHAR(2000)
AS
BEGIN
	IF NOT EXISTS (SELECT @dbFolder WHERE @dbFolder LIKE '%\')
		SET @dbFolder = @dbFolder + '\'

	RESTORE HEADERONLY FROM DISK = @backupFile

	DECLARE @File int
	SET @File = @@ROWCOUNT

	DECLARE @Data varchar(500)
	DECLARE @Log varchar(500)

	DECLARE @tempTable TABLE
	(
		[LogicalName]	NVARCHAR(MAX)	NULL,
		[PhysicalName]	NVARCHAR(MAX)	NULL,
		[Type]	NVARCHAR(MAX)	NULL,
		[FileGroupName]	NVARCHAR(MAX)	NULL,
		[Size]	BIGINT	NULL,
		[MaxSize]	BIGINT	NULL,
		[FileId]	BIGINT	NULL,
		[CreateLSN]	NUMERIC	NULL,
		[DropLSN]	NUMERIC	NULL,
		[UniqueId]	UNIQUEIDENTIFIER	NULL,
		[ReadOnlyLSN]	NUMERIC	NULL,
		[ReadWriteLSN]	NUMERIC	NULL,
		[BackupSizeInBytes]	BIGINT	NULL,
		[SourceBlockSize]	INT	NULL,
		[FileGroupId]	INT	NULL,
		[LogGroupGUID]	UNIQUEIDENTIFIER	NULL,
		[DifferentialBaseLSN]	NUMERIC	NULL,
		[DifferentialBaseGUID]	UNIQUEIDENTIFIER	NULL,
		[IsReadOnly]	BIT	NULL,
		[IsPresent]	BIT	NULL,
		[TDEThumbprint]	VARBINARY(MAX)	NULL
	)

	DECLARE @query varchar(2000)

	SET @query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(@backupFile , '''')
	INSERT @tempTable
	EXEC (@query)
	
	SELECT @Data = LogicalName 
	FROM @tempTable
	WHERE [Type] = 'D'

	SELECT @Log = LogicalName 
	FROM @tempTable
	WHERE [Type] = 'L'

	PRINT @Data
	PRINT @Log

	IF @File > 0
	BEGIN
		DECLARE @DataFile varchar(2000)
		SET @DataFile = @dbFolder + @dbName + '.mdf'

		DECLARE @LogFile varchar(2000)
		SET @LogFile = @dbFolder + @dbName + '_log.ldf'


		SET @query = 'RESTORE DATABASE [' + @dbName + '] FROM DISK = ' + QUOTENAME(@backupFile, '''') + 
				' WITH MOVE ' + QUOTENAME(@Data, '''') + ' TO ' + QUOTENAME(@DataFile, '''') + ', MOVE ' +
				QUOTENAME(@Log, '''') + ' TO ' + QUOTENAME(@LogFile, '''') + ', FILE = ' + CONVERT(varchar, @File)
		EXEC (@query)

		RETURN 1
	END

	RETURN 0
END